package com.gamecauca.android;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.gamecauca.common.ActionResolver;
import com.scoreloop.client.android.core.controller.RequestController;
import com.scoreloop.client.android.core.controller.RequestControllerException;
import com.scoreloop.client.android.core.controller.RequestControllerObserver;
import com.scoreloop.client.android.core.controller.ScoreController;
import com.scoreloop.client.android.core.controller.UserController;
import com.scoreloop.client.android.core.model.Score;
import com.scoreloop.client.android.core.model.Session;
import com.scoreloop.client.android.core.model.User;


public class ActionResolverAndroid implements ActionResolver{

	
	AndroidGame mContext;
	Handler uiThread;
	
	LayoutInflater inflater;
	View layout;
	
	AlertDialog.Builder scoreBuilder;
	AlertDialog.Builder confirmBuilder;
	AlertDialog.Builder errorBuilder;
	AlertDialog.Builder successBuilder;
	
	AlertDialog score;
	AlertDialog confirm;
	AlertDialog error;
	AlertDialog success;
	
	EditText name;
	
	ProgressDialog progress;
	
	String msgError = "";
	
	boolean flg = false;
	boolean submit = false;
	
	public ActionResolverAndroid(AndroidGame mcontext)
	{
		uiThread = new Handler();
		this.mContext = mcontext;
	
		
		
		inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
		layout = inflater.inflate(R.layout.submit_score_name,
			                               (ViewGroup) mContext.findViewById(R.id.layout_score_name));
		
		name = (EditText) layout.findViewById(R.id.txt_name);
		
		initScoreDialog();
		initConfirmDialog();
		initDialogSuccess();
   
		
	}

	@Override
	public void boot() {
		Intent intent = new Intent(mContext, LeaderboardActivity.class);
	    mContext.startActivity(intent);  
	}

	@Override
	public void showScoreDialog() {
		uiThread.post(new Runnable() {
            public void run() {
            	
            	if(!flg)
            	{
            		flg = true;
            		score.show();
            		
            	}
           	
            }
            
		});
		
	}
	//phuong3lua
	//@Override
	/*public void showAds(final boolean isShow)
	{
		uiThread.post(new Runnable() {
            public void run() {
            	AndroidGame game = (AndroidGame)mContext;
            	game.showAds(isShow);
           	
            }
            
		});	
	}*/
	public void initScoreDialog()
	{
		scoreBuilder = new AlertDialog.Builder(mContext);
    	scoreBuilder.setMessage(R.string.score_notice);
    	scoreBuilder.setTitle(R.string.score_title);
    	scoreBuilder.setIcon(mContext.getResources().getDrawable(R.drawable.sl_icon_user));
    	scoreBuilder.setPositiveButton(R.string.score_yes, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				flg = false;
				score.cancel();
				confirm.show();
			}
		});
    	
    	scoreBuilder.setNegativeButton(R.string.score_no, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				flg = false;
			}
		});
    	
    	scoreBuilder.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				flg = false;
			}
		});
    	
    	score = scoreBuilder.create();
	}
	
	public void initConfirmDialog()
	{
		confirmBuilder = new AlertDialog.Builder(mContext);
    	confirmBuilder.setView(layout);
    	confirmBuilder.setTitle(R.string.score_confirm_title);
    	confirmBuilder.setIcon(mContext.getResources().getDrawable(R.drawable.sl_icon_user));
    	confirmBuilder.setPositiveButton(R.string.score_submit_now, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				confirm.cancel();
				
				submitUserName(name.getText().toString());
				if(submit)
				{
					
				}
							
			}
		});
    	
    	confirmBuilder.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				flg = false;
			}
		});
    	
    	confirm = confirmBuilder.create();
	}
	
	public void submitUserName(String name)
	{
		User user = Session.getCurrentSession().getUser();
		user.setLogin(name);
		
		RequestControllerObserver observerName = new RequestControllerObserver() {

			@Override
			public void requestControllerDidFail(RequestController controller, Exception exception) {
				submit = false;
				msgError = "";
				
				progress.dismiss();
				if(exception instanceof RequestControllerException) {
					
					RequestControllerException ctrlException = (RequestControllerException) exception;
					
					if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TAKEN)) {
						msgError += mContext.getString(R.string.profile_error_username_taken);
					}
					else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TOO_SHORT)) {
						msgError += mContext.getString(R.string.profile_error_username_too_short);
					}
					else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_USERNAME)) {
						msgError += mContext.getString(R.string.profile_error_username_invalid);
					}
					
					initDialogError(msgError);
					error.show();
					
				}
				else
				{
					initDialogError(exception.getLocalizedMessage());
					error.show();
				}
				
			}

			@Override
			public void requestControllerDidReceiveResponse(RequestController aRequestController) {
				submit = true;
				progress.dismiss();
				submitUserScore("30");
			}
			
		};
		
		UserController userController = new  UserController(observerName);
		userController.setUser(user);
		progress = ProgressDialog.show(mContext, "", mContext.getString(R.string.loading));
		userController.submitUser();
		
		
	}
	
	public void submitUserScore(String scoreField)
	{
		double scoreResult;
		try {
			scoreResult = Double.valueOf(scoreField);
		} catch(NumberFormatException ex) {
			scoreResult = 0;
		}
		
		Score score = new Score(scoreResult, null);
		
		RequestControllerObserver observerScore = new RequestControllerObserver() {

			@Override
			public void requestControllerDidFail(RequestController controller, Exception exception) {
				msgError = exception.getLocalizedMessage();
				progress.dismiss();
				initDialogError(msgError);
				error.show();
			}

			@Override
			public void requestControllerDidReceiveResponse(RequestController controller) {
				progress.dismiss();
				success.show();
			}
			
		};
		
		ScoreController scoreController = new ScoreController(observerScore);
		progress = ProgressDialog.show(mContext, "", mContext.getString(R.string.loading));
		
		scoreController.submitScore(score);
	}
	
	public void initDialogError(String msg)
	{
		errorBuilder = new AlertDialog.Builder(mContext);
		errorBuilder.setMessage(msg);
		errorBuilder.setPositiveButton(R.string.too_bad, null);
		
		error = errorBuilder.create();
	}
	
	public void initDialogSuccess()
	{
		successBuilder = new AlertDialog.Builder(mContext);
		successBuilder.setTitle(R.string.scoreloop);
		successBuilder.setIcon(mContext.getResources().getDrawable(R.drawable.sl_icon_user));
		successBuilder.setMessage(R.string.score_submitted);
		successBuilder.setPositiveButton(R.string.awesome, null);
		
		success = successBuilder.create();
	}

	@Override
	public void showFacebook() {
		Intent intent = new Intent(mContext, FacebookActivity.class);
	    mContext.startActivity(intent);
	}

	/** 
	 * @author bangnt_vfa
	 * show twitter browse
	 */
	@Override
	public void showTwitter() {
		Intent i = new Intent(mContext, PrepareRequestTokenActivity.class);
		mContext.startActivity(i);
	}

	
	

}
